package com.justonetech.translation.controller;

import com.justonetech.core.controller.BaseCRUDActionController;
import com.justonetech.core.orm.hibernate.Page;
import com.justonetech.core.orm.hibernate.QueryTranslate;
import com.justonetech.core.utils.ReflectionUtils;
import com.justonetech.system.tree.Node;
import com.justonetech.system.tree.TreeBranch;
import com.justonetech.system.tree.ZTreeNode;
import com.justonetech.system.utils.Constants;
import com.justonetech.translation.daoservice.ProjectService;
import com.justonetech.translation.domain.Project;
import com.justonetech.translation.manager.ProjectManager;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * @version 1.0
 * @author: System
 */
@Controller
public class ProjectController extends BaseCRUDActionController<Project> {
    private static Log log = LogFactory.getLog(ProjectController.class);

    @Autowired
    private ProjectService projectService;

    @Autowired
    private ProjectManager projectManager;

    @RequestMapping
    @ResponseBody
    public Page<Project> grid(Page page, String condition) {
        try {
            page.setAutoCount(true);

            String hql = "from Project t where 1=1 order by t.id desc";

            QueryTranslate queryTranslate = new QueryTranslate(hql, condition);

            // 查询
            page = projectService.findByPage(page, queryTranslate.toString());
        } catch (Exception e) {
            log.error("error", e);
        }

        return page;
    }

    @RequestMapping
    @ResponseBody
    public Page<Project> hisGrid(Page page, String condition) {
        try {
            page.setAutoCount(true);

            String hql = "from Project t where status ="+ Constants.PROJECT_COMPLETED+" order by t.id desc";

            QueryTranslate queryTranslate = new QueryTranslate(hql, condition);

            // 查询
            page = projectService.findByPage(page, queryTranslate.toString());
        } catch (Exception e) {
            log.error("error", e);
        }

        return page;
    }

    @RequestMapping
    public String init(Model model, Project entity) throws Exception {
        try {
            if(entity != null && entity.getId() != null) {
                entity = projectService.get(entity.getId());

                model.addAttribute("bean", entity);
            }
        } catch (Exception e) {
            log.error("error", e);
        }
        if(entity.getStatus()==Constants.PROJECT_START){
            return "view/pro/projectStatusEdit";
        }
        return "view/pro/projectEdit";
    }

    @RequestMapping
    public String view(Model model, Long id) {
        Project project = projectService.get(id);

        model.addAttribute("bean", project);
        return "view/pro/projectView";
    }

    /**
     * 取得树数据
     *
     * @param type
     *            节点类型
     * @param uid
     *            节点ID
     * @throws Exception
     *             异常
     */
    @RequestMapping
    @ResponseBody
    public List<Node> tree(String type,String uid, String id) throws Exception {
        TreeBranch treeBranch = new TreeBranch();
        type = StringUtils.defaultString(type, "");

        if(StringUtils.isEmpty(uid)) {
            ZTreeNode treeNode = new ZTreeNode();
            treeNode.setId("root");
            treeNode.setIsParent(true);
            treeNode.setIsLeaf(false);
            treeNode.setOpen(true);
            treeNode.setName("项目信息");
            treeNode.setUid("root");
            treeBranch.addTreeNode(treeNode);
        } else {
            //取单位节点
            String hql ="from Project p where p.status is null or p.status!="+ Constants.PROJECT_COMPLETED;

            List<Project> projectList = projectService.findByQuery(hql);

            for (Project project : projectList) {
                ZTreeNode treeNode = new ZTreeNode();
                treeNode.setId(project.getClass().getSimpleName() + "_" + project.getId());
                treeNode.setIsLeaf(true);
                treeNode.setName(project.getName());
                treeNode.setText(project.getName());
                treeNode.setUid(project.getId().toString());
                treeNode.setType(project.getClass().getSimpleName());
                treeBranch.addTreeNode(treeNode);
            }
        }

        return treeBranch.getTreeNodeList();
    }

    @RequestMapping
    @ResponseBody
    public List <Project>getProjects(Model model) {
        return projectService.find("from Project p where p.status is null or p.status!="+ Constants.PROJECT_COMPLETED);
    }

    @RequestMapping
    @ResponseBody
    public List <Project>getAllProjects(Model model) {
        return projectService.find("from Project p ");
    }

    @RequestMapping
    public void save(HttpServletResponse response, Model model, @ModelAttribute("bean") Project entity)
            throws Exception {
        try {
            String[] columns = new String[]{
                    "id",
                    "doc",
                    "name",
                    "code",
                    "type",
                    "sourceName",
                    "souceLanguage",
                    "targetLanguage",
                    "wordCount",
                    "requirement",
                    "startDate",
                    "status",
                    "endDate"
            };

            Project target;
            if (entity.getId() != null) {
                target = projectService.get(entity.getId());

                ReflectionUtils.copyBean(entity, target, columns);

                projectService.save(target);
            } else {
                entity.setStatus(Constants.PROJECT_WAITING);
                projectManager.save(entity);
            }

            sendSuccessJSON(response, "保存成功");
        } catch (Exception e) {
            log.error("error", e);
            super.processException(response, e);
        }
    }

    @RequestMapping
    public void delete(HttpServletResponse response, Long id) throws Exception {
        projectService.delete(id);

        sendSuccessJSON(response, "删除成功");
    }

    @RequestMapping
    @ResponseBody
    public List<Project> getProjectList(String name) {
        String hql = "from Project t order by t.id desc";

        return projectService.find(hql);
    }
}